//
//  YQStatusPictureView.m
//  WeiboOC
//
//  Created by yang on 15/11/20.
//  Copyright © 2015年 yang. All rights reserved.
//

#import "YQStatusPictureView.h"
static NSString* PictureCellId = @"PictureCellId";
static CGFloat PictureCellMargin = 5;
@interface YQStatusPictureView ()
@property (nonatomic, strong) UICollectionViewFlowLayout *flowlayout;
@end
@implementation YQStatusPictureView
-(void)setImageURLs:(NSArray *)imageURLs{
    _imageURLs = imageURLs;
    [self reloadData];
    CGSize viewSize = [self calceViewSize];
    [self updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(viewSize.height);
        make.width.equalTo(viewSize.width);
    }];
}
//计算YQStatusPictureView的大小
- (CGSize)calceViewSize{
    CGFloat colum = 3.00000000001;
    CGFloat maxWidth = screenW - 2 * StatusCellMargin;
    CGFloat itemWidth = (maxWidth - 2 * PictureCellMargin) / colum;
    self.flowlayout.itemSize = CGSizeMake(itemWidth, itemWidth);
    if (self.imageURLs.count == 0) {
        return CGSizeZero;
    }
    if (self.imageURLs.count == 1) {
        NSString *key = [self.imageURLs.lastObject absoluteString];
        UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
        CGSize imageSize = image.size;
        self.flowlayout.itemSize = imageSize;
        return imageSize;
    }
    if (self.imageURLs.count == 4) {
        CGFloat w = 2 *itemWidth + PictureCellMargin;
        return CGSizeMake(w, w);
    }
    CGFloat row = (self.imageURLs.count - 1) / 3 + 1;
    CGFloat w = maxWidth;
    CGFloat h = row * itemWidth + (row - 1) * PictureCellMargin;
    return CGSizeMake(w, h);
}
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout*)layout
{
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = PictureCellMargin;
    flowLayout.minimumInteritemSpacing = PictureCellMargin;
    self.flowlayout = flowLayout;
    self = [super initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    if (self) {
        [self registerClass:[YQStatusPictureViewCell class] forCellWithReuseIdentifier:PictureCellId];
        self.backgroundColor = [UIColor whiteColor];
        self.dataSource = self;
    }
    return self;
}
//数据源方法
- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageURLs.count;
}
- (UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath
{
    YQStatusPictureViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:PictureCellId forIndexPath:indexPath];
    cell.backgroundColor = [UIColor randomColor];
    cell.url = self.imageURLs[indexPath.item];
    return cell;
}

@end
